package org.example.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
public class XmlUtil {
    public static String xml2json(String requestBody) {
        requestBody = StringUtils.trim(requestBody);
        XmlMapper xmlMapper = new XmlMapper();
        JsonNode node = null;
        try {
            node = xmlMapper.readTree(requestBody.getBytes());
            ObjectMapper jsonMapper = new ObjectMapper();
            return jsonMapper.writeValueAsString(node);
        } catch (Exception e) {
            log.error("xml 2 json error,msg:" + e.getMessage(), e);
        }
        return null;
    }


    public static Map<String, String> xmlToMap(InputStream inputStream) {
        Map<String, String> map = new HashMap<>();
        try {
            SAXReader reader = new SAXReader();
            org.dom4j.Document document = reader.read(inputStream);
            Element root = document.getRootElement();
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList)
                map.put(e.getName(), e.getText());
            // 释放资源
            inputStream.close();
        } catch (IOException | DocumentException e) {
            log.info("xml转化为map出现异常：{}", e.getMessage());
        }
        return map;
    }
}

